<?php
// +----------------------------------------------------------------------
// | 租户授权管理 类型服务
// +----------------------------------------------------------------------
// | 主要服务于租户机器人授权管理数据处理
// +----------------------------------------------------------------------
// | 错误编码头 302xxx
// +----------------------------------------------------------------------

namespace common\service;


use common\model\TenantRobotUserCertificateModel;
use common\model\TenantUserModel;
use common\model\UserModel;

class TenantRobotUserCertificateService
{
    /**
     * @var TenantRobotUserCertificateModel
     */
    private $tenantRobotUserCertificateModel;
    /**
     * @var TenantUserModel
     */
    private $tenantUserModel;


    public function __construct()
    {
        $this->tenantRobotUserCertificateModel = model(TenantRobotUserCertificateModel::class);
        $this->tenantUserModel = model(TenantUserModel::class);
        $this->tenantService = new TenantService();
    }

    /**
     * 给机器人生成秘钥证书
     * @param array $data
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function create(array $data)
    {
        // 检查机器人是否在租户里 不在的话 自动加入租户
        $tenantUser = $this->tenantUserModel->where(['tenant_id' => $data['tenant_id'], 'user_id' => $data['user_id']])->find();
        if (empty($tenantUser)) {
            $tenantUser = $this->tenantUserModel->addItem([
                'user_id' => $data['user_id'],
                'tenant_id' => $data['tenant_id'],
            ]);
            if (empty($tenantUser)) {
                throw_strack_exception($this->tenantUserModel->getError(), $this->tenantUserModel->getErrorCode());
            }
        }
        // 检查存不存在秘钥对 存在就更新
        $certificate = $this->tenantRobotUserCertificateModel->where(['tenant_user_id' => $tenantUser['id']])->find();
        if (empty($certificate)) {
            $data['tenant_user_id'] = $tenantUser['id'];
            $data['active'] = "1";
            $certificate = $this->tenantRobotUserCertificateModel->addItem($data);
        } else {
            $data['id'] = $certificate['id'];
            $data['app_key'] = auto_fill_md5_str();
            $data['app_secret'] = auto_fill_md5_str();
            $data['active'] = "1";
            $certificate = $this->tenantRobotUserCertificateModel->modifyItem($data);
        }
        if ($certificate === false) {
            throw_strack_exception($this->tenantRobotUserCertificateModel->getError(), $this->tenantRobotUserCertificateModel->getErrorCode());
        }
        return $certificate;
    }

    /**
     * 查询机器人信息
     * @param string $code
     * @param int $tenantId
     * @return array|null
     * @throws \Exception
     */
    public function findByCode(string $code, int $tenantId)
    {
        $user = UserService::getInstance()->getSystemNoticeUser($code);
        if (empty($user)) {
            return null;
        }

        $where = $param['filter'] ?? [];
        $where['user.id'] = $user['id'];
        $fields = [
            "user.id",
            "user.name",
            "user.email",
            "user.phone",
            "user.status",
            "user.created",
            "user.is_system",
            "tenant_user.id",
            "tenant_user.tenant_id",
            "tenant_user.user_id",
            "tenant_robot_user_certificate.id",
            "tenant_robot_user_certificate.app_key",
            "tenant_robot_user_certificate.app_secret",
            "tenant_robot_user_certificate.active",
            "tenant_robot_user_certificate.uuid",
        ];
        $fields = build_complex_query_fields($fields, "__");
        $fields = implode(',', $fields);


        $res = model(UserModel::class)
            ->join("tenant_user ON tenant_user.user_id = user.id AND tenant_user.tenant_id={$tenantId}", 'LEFT')
            ->join('tenant_user_department on tenant_user.id = tenant_user_department.tenant_user_id', 'LEFT')
            ->join('tenant_user_role on tenant_user.id = tenant_user_role.tenant_user_id', 'LEFT')
            ->join('department ON tenant_user_department.department_id = department.id', 'LEFT')
            ->join('role ON role.id = tenant_user_role.role_id', 'LEFT')
            ->join('tenant_robot_user_certificate ON tenant_user.id = tenant_robot_user_certificate.tenant_user_id', 'LEFT')
            ->where($where)
            ->field($fields)
            ->find();

        $tenantUserDepartmentRoleInfoList = TenantUserService::getInstance()->getTenantUserListDepartmentRole([$res['tenant_user__id']]);
        $res = separate_complex_query_data($res, "__");
        $res['department_info'] = $res['role_info'] = [];
        if (isset($tenantUserDepartmentRoleInfoList[$res['tenant_user']['id']])) {
            $res = array_merge($res, $tenantUserDepartmentRoleInfoList[$res['tenant_user']['id']]);
        }
        return $res;
    }
}
